package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    //登录默认需要将数据传到这个方法中
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询到对应的用户数据
        User user = userService.findByUserName(username);
        if (user == null){
            //表示用户不存在
            return null;
        }
        //用户存在，则获取用户的角色信息
        Set<Role> roles = user.getRoles();
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        if (roles != null){
            for (Role role : roles) {
                //将角色信息放入角色权限管理的集合中
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null){
                    for (Permission permission : permissions) {
                        //将权限信息存放发到角色权限管理的集合中
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //将用户名、密码、权限集合放到security定义的user对象中进行返回
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
